package com.googlecode.jsitemap.sitemap;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;

import com.googlecode.jsitemap.BuildParams;
import com.googlecode.jsitemap.BuilderBase;
import com.googlecode.jsitemap.Entry;

/**
 * @author Denis Migol
 * 
 */
public class SitemapTXTBuilderImpl extends BuilderBase<Entry, BuildParams> implements
		SitemapTXTBuilder<Entry, BuildParams> {

	public SitemapTXTBuilderImpl(final BuildParams params) {
		super(params);
	}

	@Override
	public int build(final OutputStream out, final Collection<Entry> entries) throws IOException {
		final byte[] newLine = newLine();
		final int newLineLength = newLine.length;

		int ret = 0;
		boolean first = true;
		// for (final Entry entry : entries) {
		for (final Iterator<Entry> iterator = entries.iterator(); iterator.hasNext();) {
			final Entry entry = iterator.next();

			final byte[] entryBytes = buildEntry(entry);
			if (first) {
				final int length = entryBytes.length;
				if (canWrite(ret, length)) {
					out.write(entryBytes);

					ret += length;
				} else {
					break;
				}
				first = false;
			} else {
				final int length = newLineLength + entryBytes.length;
				if (canWrite(ret, length)) {
					out.write(newLine);
					out.write(entryBytes);

					ret += length;
				} else {
					break;
				}
			}
			if (params.isModifyEntries()) {
				iterator.remove();
			}
		}
		return ret;
	}

	@Override
	protected byte[] buildEntry(final Entry entry) {
		return getBytes(entry.getLoc());
	}

}
